package com.liu.yubi.config;

import com.github.rholder.retry.*;
import com.liu.yubi.exception.BusinessException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;

/**
 * @author lqh
 * @since 2025-06-06 15:15
 * guava重试机制
 */
@Configuration
public class GuavaRetryingConfig {

    @Bean
    public  Retryer<Boolean> retryer(){
        // 构建 Retryer 实例
        return RetryerBuilder.<Boolean>newBuilder()
                // 重试条件：捕获 BusinessException 重试
                .retryIfExceptionOfType(BusinessException.class)
                // 重试策略：最多重试 3 次，使用指数退避延迟（初始 1 秒，每次倍增，最大 5 秒）
                .withWaitStrategy(WaitStrategies.exponentialWait(1, 5, TimeUnit.SECONDS))
                .withStopStrategy(StopStrategies.stopAfterAttempt(3))
                // 重试监听器：记录重试过程
                .withRetryListener(new RetryListener () {
                    @Override
                    public <T> void onRetry(Attempt<T> attempt) {
                        //有异常
                        if (attempt.hasException ()){
                            System.out.println("重试第 " + attempt.getAttemptNumber() + " 次，原因：" + attempt.getExceptionCause());
                        }else {
                            System.out.println ("结果为:"+attempt.getResult ()+",任务执行成功!");
                        }
                    }
                })
                .build();
    }
}
